package com.ldn.basic.utils.qiniu;


import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author 李大牛家的牛 (scafel@163.com) 
 * @createDate 2024/9/30 - 11:14
 * @description ...
 **/
@Slf4j
@Component
public class QNOssUtil {

    public static void uploadToOss(String accessKeyId, String accessKeySecret, String bucket, String endpoint,String folderName, File file) {
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKeyId, accessKeySecret);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file, folderName + file.getName(), upToken);
        } catch (QiniuException ex) {
            log.error("上传文件到七牛云失败", ex);
            if (ex.response != null) {
                try {
                    String body = ex.response.toString();
                    throw new RuntimeException(body);
                } catch (Exception ignored) {}
            }
            throw new RuntimeException(ex.getMessage());
        } catch (Exception ex){
            log.error("文件上传失败", ex);
            throw new RuntimeException(ex.getMessage());
        }
    }
}
